/*
 * Copyright (C) 2021 Huawei Device Co., Ltd.
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package com.facebook.fresco.helper.utils;

import ohos.agp.components.element.Element;
import ohos.agp.components.element.PixelMapElement;
import ohos.agp.render.BlendMode;
import ohos.agp.render.Canvas;
import ohos.agp.render.Paint;
import ohos.agp.render.PixelMapHolder;
import ohos.agp.render.Texture;
import ohos.agp.utils.Color;
import ohos.media.image.ImageSource;
import ohos.media.image.PixelMap;
import ohos.media.image.common.PixelFormat;

import com.oszc.bbhmlibrary.wrapper.RectF;

/**
 * 圆图变换
 *
 * @author dev
 * @since 2021-08-04
 */
public class CircleBitmapTransform {
    private static final int CONSTANT = 2;

    private CircleBitmapTransform() {
    }

    /**
     * 变换
     *
     * @param toTransform 转换
     * @return {@link PixelMap}
     */
    public static PixelMap transform(PixelMap toTransform) {
        if (toTransform == null) {
            return null; // 返回空
        }
        int bitmapWidth = toTransform.getImageInfo().size.width;
        int bitmapHeight = toTransform.getImageInfo().size.height;

        PixelMap.InitializationOptions options = new PixelMap.InitializationOptions();
        options.size = toTransform.getImageInfo().size;
        options.size.width = bitmapWidth;
        options.size.height = bitmapHeight;
        options.pixelFormat = PixelFormat.ARGB_8888;
        PixelMap output = PixelMap.create(options);

        Canvas canvas = new Canvas(new Texture(output));
        RectF outerRect = new RectF();
        outerRect.set(0, 0, bitmapWidth, bitmapHeight);

        Paint paint = new Paint();
        paint.setAntiAlias(true);
        paint.setColor(Color.WHITE);
        int cornerRadius = Math.min(bitmapWidth / CONSTANT, bitmapHeight / CONSTANT);
//        canvas.drawPixelMapHolderCircleShape(new PixelMapHolder(toTransform), outerRect, cornerRadius, cornerRadius, cornerRadius);
        canvas.drawRoundRect(outerRect, cornerRadius, cornerRadius, paint);
        paint.setBlendMode(BlendMode.SRC_IN);
        Element drawable = new PixelMapElement(toTransform);
        drawable.setBounds(0, 0, bitmapWidth, bitmapHeight);

        canvas.saveLayer(outerRect, paint);
        drawable.drawToCanvas(canvas);

        return output;
    }
}
